﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TLECDataLayer;

namespace EventManager
{
    public partial class LocationForm : Form
    {
        private Location selectedLocation;

        public LocationForm()
        {
            InitializeComponent();
            WinLoad();
        }

        private void WinLoad()
        {
            this.locationBindingSource.DataSource = Locations.GetAllLocations();
        }

        private void locationsDGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != this.locationsDGV.Rows.Count - 1 && e.RowIndex != -1)
            {
                selectedLocation = Locations.GetLocationById(((Location)this.locationsDGV.Rows[e.RowIndex].DataBoundItem).LocationId);
                this.locNameTxt.Text = selectedLocation.LocationName;
            }
            else
            {
                this.locNameTxt.Text = "";
                selectedLocation = null;
            }
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            if (selectedLocation != null && !string.IsNullOrEmpty(this.locNameTxt.Text))
            {
                Locations.UpdateLocation(selectedLocation.LocationId, this.locNameTxt.Text);
                MessageBox.Show("Changes have been saved");
            }
            else if (!string.IsNullOrEmpty(this.locNameTxt.Text))
            {
                Locations.CreateLocation(this.locNameTxt.Text);
                MessageBox.Show("New location has been added");
            }
            WinLoad();
        }

        private void deleteBtn_Click(object sender, EventArgs e)
        {
            if (selectedLocation != null)
            {

                if (TLECDataLayer.Events.GetAllEventsByLocation(selectedLocation.LocationId).Count() == 0)
                {
                    Locations.DeleteLocation(selectedLocation.LocationId);
                    MessageBox.Show("The selected item has been deleted");
                }
                else
                {
                    MessageBox.Show("You can not delete this location because there are events with it!");
                }
            }
            else
            {
                MessageBox.Show("Select some item first.");
            }
            WinLoad();
        }
    }
}
